# encoding=utf-8
import traceback

import flask
import os
from seg_system import ApplicationConfig
from seg_common.annotation import CommonAnnotation
from seg_common import DirMakeFactory
from seg_common.parser import ParserTools


class DownloadDirFactory(DirMakeFactory):
    def __init__(self):
        super(DownloadDirFactory, self).__init__()
        self.NORMAL_0 = ""
        self.NORMAL_1 = ""

    @CommonAnnotation.override()
    def path_init_with_request(self, request: flask.Request, save_dir: str = None):
        user_name, token = ParserTools.parser_name_token_from_request(request)
        return self.temp_dir_create(save_dir=save_dir, user_name=user_name, token=token)

    @CommonAnnotation.override()
    def path_init(self, **kwargs):
        save_dir, user_name, token = super().base_parser(**kwargs)
        if user_name:
            USER_FOLDER = os.path.join(ApplicationConfig.PathConfig.BASE_SAVE_PATH,
                                       user_name)
        else:
            USER_FOLDER = os.path.join(ApplicationConfig.PathConfig.BASE_SAVE_PATH,
                                       ApplicationConfig.PathConfig.DEFAULT_USER_NAME)

        if save_dir:
            USER_FOLDER = os.path.join(save_dir, USER_FOLDER)

        self.NORMAL_0 = os.path.join(USER_FOLDER, ApplicationConfig.PathConfig.USER_TMP_FOLDER)
        if token:
            self.NORMAL_1 = os.path.join(USER_FOLDER, token)
        else:
            self.NORMAL_1 = os.path.join(USER_FOLDER, ApplicationConfig.PathConfig.DEFAULT_USER_TOKEN)
        return self.NORMAL_0

    @CommonAnnotation.override()
    def temp_dir_create(self, **kwargs):
        USER_FOLDER = self.path_init(**kwargs)
        if os.path.exists(USER_FOLDER):
            return True, [{'name': USER_FOLDER, 'success': 'ok'}]
        try:
            ApplicationConfig.PathConfig.make_dir(self.NORMAL_0)
        except Exception as e:
            print(traceback.format_exc())
            return False, [{'name': USER_FOLDER, 'error': str(e)}]
        return True, [{'name': USER_FOLDER, 'success': 'ok'}]
